/*
 * IPhisicsObject.cpp
 *
 *  Created on: 03.03.2012
 *      Author: Kirill Blinov
 *      Copyright: LGPL
 */

#include "../../BasicTypes.h"
#include "IPhysicsObject.h"
#include "PhysicsEngine.h"
#include <glm/gtc/quaternion.hpp>

IPhysicsObject*
PhysicObjectFabric::CreatePhysicsObject( const float Mass, glm::quat  Orientation, const glm::vec3 Position,
                                         const glm::vec3 Box[2], const glm::vec3 Inertia,
                                         const PHYSICS_OBJECT_BODY_PARAM &bodyParam  )
{
    btCollisionShape     *shape;
    btMotionState        *motionState;
	PhysicsEngine *Engine = PhysicsEngine::GetPhysicsEngine();

    glm::vec3 Sizes = ( Box[0] - Box[1] ) / 2.0f;
    shape = new btBoxShape( btVector3( Sizes.x, Sizes.y, Sizes.z) );

    btTransform trans;
    trans.setIdentity();

    btQuaternion qtn;
    glm::vec3 EulerAngles = glm::eulerAngles( Orientation );
    qtn.setEuler( EulerAngles.x, EulerAngles.y , EulerAngles.z );

    trans.setRotation( qtn );
    trans.setOrigin( btVector3( Position.x, Position.y, Position.z ) );
    motionState = new btDefaultMotionState( trans );

    btVector3 TmpInertia( Inertia.x, Inertia.y, Inertia.z );
    if ( ( 0.0f == Inertia.x ) &&   ( 0.0f == Inertia.y ) &&  ( 0.0f == Inertia.z ) )
    {
            shape->calculateLocalInertia( Mass, TmpInertia);
    }

    btRigidBody::btRigidBodyConstructionInfo RigidBodyConstructionInfo(  btScalar(Mass), motionState, shape, TmpInertia );
    RigidBodyConstructionInfo.m_restitution = bodyParam.restitution;
    RigidBodyConstructionInfo.m_friction = bodyParam.friction;
    RigidBodyConstructionInfo.m_linearDamping = bodyParam.linearDamping;
    RigidBodyConstructionInfo.m_angularDamping = bodyParam.angularDamping;

    btRigidBody *NewBody = new btRigidBody( RigidBodyConstructionInfo );
    IPhysicsObject *ResultObject = new CRigidConvexPhisicsObject( NewBody );
    Engine->AddPhisicsObject( *ResultObject );

	return ResultObject;
}

void
PhysicObjectFabric::DeletePhysicsObject( IPhysicsObject* Object )
{
	PhysicsEngine *Engine = PhysicsEngine::GetPhysicsEngine();
	Engine->RemovePhisicsObject( *Object );
	delete Object;

}

//----------------------------------//

IPhysicsObject::IPhysicsObject( btCollisionObject *PhysicsObject ) :
					physicsObject(PhysicsObject)
{

}

IPhysicsObject::~IPhysicsObject()
{
	delete physicsObject;
}

